<?php
declare (strict_types=1);

namespace app\api\controller\v2;

use app\api\validate\LoginValidate;
use app\api\validate\ArticleValidate;
use app\api\validate\QuestionValidate;
use app\common\model\ApiMember;
use app\common\model\Cate;
use app\common\model\QuestionZan;
use think\exception\ValidateException;
use app\common\model\Question;
use think\facade\Filesystem;
use app\common\model\Article;

class Personal extends BaseController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        //
        return sucessMsg('200', '获取成功', [
            'per' => $this->per(),//获取个人信息展示
        ]);
    }

    /**
     * 获取个人中心信息展示
     */
    public function per()
    {
        $per = ApiMember::where(['status' => 1, 'id' => $this->user_id])
            ->field('id,account,username,image,phone,login_times')
            ->withAttr('image', function ($val, $data) {
                return env('app.yuming') . $val;
            })
            ->find();
        $per['login_times'] = date('Y-m-d');
        return $per;
    }

    /**
     * 个人中心信息修改
     */
    public function editper()
    {
        $postData = input('post.');
        try {
            //  验证参数
            validate(LoginValidate::class)->scene('edit')->check($postData);
            $user = new ApiMember();
            if (!empty($postData['password'])) {
                $postData['salt'] = getRandStr(6);
                $postData['password_hash'] = makePassword($postData['password'], $postData['salt']);
            }
            if (!empty($postData['image'])) {
                $postData['image'] = str_replace(env('app.yuming'), '', $postData['image']);
            } else {
                unset($postData['image']);
            }
            if ($user->where(['id' => $this->user_id])->save($postData)) {
                return sucessMsg(200, '修改成功');
            }
            return errMsg(422, '修改失败，请重试！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    //上传图片
    public function upload()
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file();
        if (empty($file))
            return errMsg(400, '请上传文件!');
        $k = array_keys($file);
        $saveName = Filesystem::disk('upload')->putFile('/uploads', $file[$k[0]]);
        if (!empty($saveName)) {
            $saveName = str_replace('\\', "/", $saveName);
            $saveName = env('app.yuming') . $saveName;
            return sucessMsg(200, '上传成功', $saveName);
        }
    }

    /**
     * 个人中心问题提交
     */
    public function subproblem()
    {
        $data = input();
        if (empty($data['title'])) {
            return errMsg('400', '请输入问题标题');
        }
        if (empty($data['content'])) {
            return errMsg('400', '请输入问题内容');
        }
        $data['member_id'] = $this->user_id;
        $data['name'] = ApiMember::where('id', $data['member_id'])->value('username');
        $data['cate_id'] = rand(5, 7);
        $data['label'] = '问答';
        $data['picture'] = $data['image'] = rand(1, 10);
        $data['status'] = 3;
        $ques = New Question();
        $sub = $ques->save($data);
        if ($sub) {
            return sucessMsg('200', '提交成功');
        }
        return errMsg('400', '系统繁忙，请稍后再试');
    }

    /**
     * 个人中心问题提交
     */
    public function problems()
    {
        $page = input('page/d', 1);
        $listRows = 3;
        $member_id = $this->user_id;
        $where = [
            ['status', '=', 3],
            ['member_id', '=', $member_id]
        ];
        $problems = Question::where($where)
            ->field('id,title,content,zan_num,col_num,comment_num,created_at')
            ->order('id', 'desc')
            ->page($page, $listRows)
            ->select();
        $count = Question::where($where)->count();
        $maxpage = ceil($count / $listRows);
        return sucessMsg('200', '获取成功', ['problems' => $problems, 'page' => $page, 'maxpage' => $maxpage]);
    }

    /**
     * 系统消息
     */
    public function tongzhi()
    {
        $page = input('page/d', 1);
        $listRows = 3;
        $member_id = $this->user_id;
        $model = New QuestionZan();
        $tongzhi = $model->where('member_id', $member_id)
            ->with(['getmember', 'getquestion'])
            ->field('id,member_id,zan_member_id,question_id,created_at')
            ->page($page, $listRows)
            ->order('created_at', 'desc')
            ->select()->toArray();
        foreach ($tongzhi as &$v) {
            $v['username'] = $v['getmember']['username'];
            $v['image'] = $v['getmember']['image'];
            unset($v['getmember']);
            $v['kong'] = 1;
            if (empty($v['getquestion'])) {
                $v['kong'] = '';
            } else {
                $v['question_id'] = $v['getquestion']['id'];
                $v['title'] = $v['getquestion']['title'];
                $v['zan_num'] = $v['getquestion']['zan_num'];
                unset($v['getquestion']);
                $v['image'] = env('app.yuming') . $v['image'];
            }
        }
        $count = $model->where('member_id', $member_id)->count();
        $maxpage = ceil($count / $listRows);
        return sucessMsg('200', '获取成功', ['tongzhi' => $tongzhi, 'page' => $page, 'maxpage' => $maxpage]);
    }

    //获取分类
    public function cate()
    {
        $article = Cate::where(['status' => 1, 'type' => 4])
            ->field('id,name')
            ->select();
        $question = Cate::where(['status' => 1, 'type' => 3])
            ->field('id,name')
            ->select();
        return sucessMsg(200, '获取成功', ['article' => $article, 'question' => $question]);
    }

    //发布文章
    public function reaArticle()
    {
        $postData = input('post.');
        $postData['member_id'] = $this->user_id;
        $postData['name'] = ApiMember::where('id', $postData['member_id'])->value('username');
        try {
            validate(ArticleValidate::class)->scene('save')->check($postData);
            $postData['image'] = str_replace(env('app.yuming'), '', $postData['image']);
            $postData['picture'] = str_replace(env('app.yuming'), '', $postData['picture']);
            if (Article::insert($postData)) {
                return sucessMsg(200, '发布成功');
            }
            return errMsg(400, '添加失败，请稍后再试');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    //我发布的文章
    public function Article()
    {
        $page = input('page/d', 1);
        $listRows = 3;
        $member_id = $this->user_id;
        $data = Article::where(['status' => 1, 'member_id' => $member_id])
            ->field('id,picture,title,content,zan_num,comment_num,col_num,created_at')
            ->order('created_at', 'desc')
            ->page($page, $listRows)
            ->withAttr('picture', function ($val, $data) {
                return env('app.yuming') . $val;
            })->select();
        $count = Article::where(['status' => 1, 'member_id' => $member_id])->count();
        $maxpage = ceil($count / $listRows);
        return sucessMsg(200, '获取成功', ['data' => $data, 'count' => $count, 'page' => $page, 'maxpage' => $maxpage]);
    }

    //发布问答
    public function reaQuestion()
    {
        $postData = input('post.');
        $postData['member_id'] = $this->user_id;
        $postData['name'] = ApiMember::where('id', $postData['member_id'])->value('username');
        try {
            validate(QuestionValidate::class)->scene('save')->check($postData);
            $postData['picture'] = str_replace(env('app.yuming'), '', $postData['picture']);
            $postData['image'] = str_replace(env('app.yuming'), '', $postData['image']);
            if (Question::insert($postData)) {
                return sucessMsg(200, '发布成功');
            }
            return errMsg(400, '发布失败，请稍后再试！');
        } catch (ValidateException $e) {
            return errMsg(400, $e->getError());
        }
    }

    //我发布的问答
    public function question()
    {
        $page = input('page/d', 1);
        $listrows = 3;
        $member_id = $this->user_id;
        $where = [
            ['status', '=', 1],
            ['member_id', '=', $member_id]
        ];
        $data = Question::where($where)
            ->field('id,picture,title,content,zan_num,comment_num,col_num,created_at')
            ->order('created_at', 'desc')
            ->page($page, $listrows)
            ->withAttr('picture', function ($val, $data) {
                return env('app.yuming') . $val;
            })->select();
        $count = Question::where($where)->count();
        $maxpage = ceil($count / $listrows);
        return sucessMsg(200, '获取成功', ['maxpage' => $maxpage, 'data' => $data, 'count' => $count, 'page' => $page]);
    }

    //删除我发布的文章
    public function delArticle()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            return errMsg(422, 'id不能为空');
        }
        $data = Article::where('id', $id)->count();
        if ($data == 0)
            return errMsg(422, '无效id');
        if (Article::destroy($id)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(422, '删除失败');
    }

    //删除我发布的问答
    public function delQuestion()
    {
        $id = input('id/d', 0);
        if (empty($id)) {
            return errMsg(422, 'id不能为空');
        }
        $data = Question::where('id', $id)->count();
        if ($data == 0)
            return errMsg(422, '无效id');
        if (Question::destroy($id)) {
            return sucessMsg(200, '删除成功！');
        }
        return errMsg(422, '删除失败');
    }
}

